import { CloseCircleOutlined } from '@ant-design/icons'
import { Button, Card, Col, DatePicker, Form, Input, Popover, Row, Select, TreeSelect, Spin, Cascader } from 'antd'
import React, { useEffect, useState } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect, history } from 'umi'
import EducationTableForm from './components/EducationTableForm'
import SocietyTableForm from './components/SocietyTableForm'
import InOrgNameTableForm from './components/InOrgNameTableForm'
import FamilyTableForm from './components/FamilyTableForm'
import FooterToolbar from './components/FooterToolbar'
import moment from 'moment'
import styles from './style.less'
import './index.less'
import {
  genderList,
  maritalList,
  socialTraineeStateArray,
  nationList,
  regionList,
  healthsList,
  yesOrNoList,
  inOrgList,
  jobLevelTypeList,
  channelList,
  probationDayList
} from '@/utils/constant'
import { getJobByOrgId,getNativeplace } from '@/pages/Info/service'
import { findItemByTree } from '@/utils/functions'

const { Option } = Select
const FormItem = Form.Item

const colStyle = {
  xl: {
    span: 6,
    offset: 1,
  },
  lg: 8,
  md: 12,
  sm: 24,
  xs: 24,
}

const Edit = ({ submitting, dispatch, match, infoAndEdit = {}, infoModel }) => {

  const { options = {} } = infoModel
  const { orgTree = [], orgLine = [], orgSystem = [], jobLevel = []} = options

  let { info } = infoAndEdit
  const [form] = Form.useForm()
  const [error, setError] = useState([])
  const [unitTree, setUnitTree] = useState(orgTree)
  const [jobList, setJobList] = useState([])
  const [jobSelectLevel, setJobSelectLevel] = useState(jobLevel)
  const [nativePlaces,setNativePlaces] = useState([])
  const { employeeId } = match.params
  useEffect(() => {
    reloadData()
    getNativeplaceList()
  }, [])

  const getNativeplaceList =() =>{
    getNativeplace().then((res = []) => {
      setNativePlaces(res)
    })
  }

  const reloadData = () => {
    if (dispatch) {
      return dispatch({
        type: 'infoAndEdit/getEmployeeById',
        payload: employeeId,
      })
    }
  }
  info = {
    ...info,
    birthday: info.birthday ? moment(info.birthday) : undefined,
    beginworkdate: info.beginworkdate ? moment(info.beginworkdate) : undefined,
    hiredate: info.hiredate ? moment(info.hiredate) : undefined,
    orgId:info.orgId ? parseInt(info.orgId):undefined,
    unitId:info.unitId ? parseInt(info.unitId):undefined,

  }

  useEffect(() => {
    if (info) {
      let { nativeplace, nativeplaceProvince, ...data} = info;
      let showNativeplace = [''];
      if (nativeplace && nativeplace!==nativeplaceProvince){
        showNativeplace = [parseInt(nativeplaceProvince), parseInt(nativeplace)];
      }else if(nativeplace && nativeplace===nativeplaceProvince){
        showNativeplace = [parseInt(nativeplace)];
      }
      form.setFieldsValue({...data, nativeplace: showNativeplace});
      const item = findItemByTree(orgTree, info.orgId)
      setUnitTree(item ? item.children : [])
      info.unitId && getJobByOrgId(info.unitId).then((res) => {
        setJobList(res)
      })
      if (info.jobLevelType === '2') {
        setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK'))
      } else if (info.jobLevelType === '1') {
        setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK'))
      }
    }
  }, [infoAndEdit])


  const getErrorInfo = (errors) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length

    if (!errors || errorCount === 0) {
      return null
    }

    const scrollToField = (fieldKey) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`)

      if (labelNode) {
        labelNode.scrollIntoView(true)
      }
    }

    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null
      }
      const key = err.name[0]
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon}/>
          <div className={styles.errorMessage}>{err.errors[0]}</div>
        </li>
      )
    })

    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode
            }
            return trigger
          }}
        >
          <CloseCircleOutlined/>
        </Popover>
        {errorCount}
      </span>
    )
  }

  const setNativePlaceLabel = (label) =>{
    if (typeof label !== 'string'){
      return label.join('');
    }else {
      return [label].join('');
    }
  };

  const onFinish = (values) => {
    let {nativeplace, ...data} = values;
    data.nativeplaceProvince = nativeplace[0];
    if (nativeplace.length>1){
      data.nativeplace = nativeplace[1];
    }else {
      data.nativeplace = nativeplace[0];
    }
    setError([]);
    dispatch({
      type: 'infoAndEdit/updateMainInfo',
      payload: {
        ...data,
        oid: employeeId,
        updateHireDate:moment(info.hiredate).format('YYYY-MM-DD')
      },
    })
    history.goBack()
  }

  const onFinishFailed = (errorInfo) => {
    setError(errorInfo.errorFields)
  }

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }

  const onChangeOrgId = (e) => {
    form.setFieldsValue({ unitId: undefined, jobId: undefined})
    const item = findItemByTree(orgTree, e)
    setUnitTree(item ? item.children : [])
  }

  const onChangeUnitId = (e) => {
    form.setFieldsValue({ jobId: undefined})
    getJobByOrgId(e).then((res) => {
      setJobList(res)
    })
  }

  const onChangeJobLevelType = (e) => {
    form.setFieldsValue({ jobLevelId: undefined})
    if (e === 2) {
      setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK').reverse())
    } else {
      setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK').reverse())
    }
  }

  return (
    info.name ?
      <Form
        form={form}
        layout="vertical"
        hideRequiredMark
        initialValues={info}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <div className='info-edit'>
          <PageHeaderWrapper title={info.name}>
            <Card title="基本信息" className={styles.card} bordered={false}>
              <Row gutter={24}>

                <Col {...colStyle}>
                  <FormItem label={'姓名'} name="name">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'性别'} name="gender">
                    <Select placeholder="请选择">
                      {genderList.map((item, index) => {
                        return (
                          <Option value={`${item.value}`} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'身份证'} name="idcard">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'民族'} name="nationality">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {nationList.map((item, index) => {
                        return (
                          <Option value={`${item.value}`} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'籍贯'} name="nativeplace">
                    <Cascader fieldNames={{label: 'title', value: 'value', children: 'children'}} displayRender={(label) => setNativePlaceLabel(label)} placeholder="请输入" options={nativePlaces} />
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'国籍'} name="nation">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {regionList.map((item, index) => {
                        return (
                          <Option value={`${item.value}`} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'政治面貌'} name="polity">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {inOrgList.map((item, index) => {
                        return (
                          <Option value={`${item.value}`} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'户口所在地'} name="regresidence">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'家庭住址'} name="address">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'健康状态'} name="healthstatus">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {healthsList.map((item, index) => {
                        return (
                          <Option value={`${item.value}`} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'电子邮箱'} name="privatemail">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'生日'} name="birthday">
                    <DatePicker placeholder="请选择日期" style={{ width: '100%' }}/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'手机'} name="mobile">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'参加工作时间'} name="beginworkdate">
                    <DatePicker placeholder="请选择日期" style={{ width: '100%' }}/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'婚姻状况'} name="marital">
                    <Select placeholder="请选择">
                      {maritalList.map((item, index) => {
                        return (
                          <Option value={`${item.value}`} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'是否退伍兵'} name="disbandment">
                    <Select placeholder="请选择">
                      {yesOrNoList.map((item, index) => {
                        return (
                          <Option value={`${item.value}`} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'退伍军人编号'} name="veteranNum">
                    <Input placeholder="请输入退伍军人编号"/>
                  </FormItem>
                </Col>
              </Row>
            </Card>

            <Card title="任职信息" className={styles.card} bordered={false}>
              <Row gutter={16}>
                <Col {...colStyle}>
                  <FormItem label={'公司'} name="orgId">
                    <TreeSelect treeData={orgTree} onChange={onChangeOrgId}/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'部门'} name="unitId">
                    <TreeSelect treeData={unitTree} onChange={onChangeUnitId}/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'职位'} name="jobId">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {jobList.map((item, index) => {
                        return (
                          <Option value={`${item.coidassignedjob}`} key={item.coidassignedjob}>
                            {item.cname}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'工作地点'} name="workAddress">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem name="jobSystemId" label="体系">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {orgSystem.map((item, index) => {
                        return (
                          <Option value={`${item.id}`} key={item.id}>
                            {item.name}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem name="lineId" label="条线">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {orgLine.map((item, index) => {
                        return (
                          <Option value={`${item.id}`} key={item.id}>
                            {item.name}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'工号'} name="code">
                    <Input disabled={true} placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem name="jobLevelType" label="职级类型">
                    <Select placeholder="请选择" showSearch filterOption={filterOption} onChange={onChangeJobLevelType}>
                      {jobLevelTypeList.map((item, index) => {
                        return (
                          <Option value={item.value} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem name="jobLevelId" label="职级">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {
                        jobLevel.map((item, index) => {
                          return (
                            <Option value={item.id} key={item.name}>
                              {item.name}
                            </Option>
                          )
                        })
                      }
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'入职日期'} name="hiredate">
                    <DatePicker placeholder="请选择日期" style={{ width: '100%' }}/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem name="probationday" label="试用期" rules={[{required: true, message: '试用期不能为空'}]}>
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {probationDayList.map((item, index) => {
                        return (
                          <Option value={item.value} key={item.value}>
                            {item.label}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

              </Row>
            </Card>

            {/*<Card title="薪酬信息" className={styles.card} bordered={false}>*/}
            {/*  <Row gutter={16}>*/}
            {/*    <Col {...colStyle}>*/}
            {/*      <FormItem label={'基本工资'} name="monthlySalary">*/}
            {/*        <Input placeholder="请输入"/>*/}
            {/*      </FormItem>*/}
            {/*    </Col>*/}

            {/*    <Col {...colStyle}>*/}
            {/*      <FormItem label={'模块绩效'} name="performance">*/}
            {/*        <Input placeholder="请输入"/>*/}
            {/*      </FormItem>*/}
            {/*    </Col>*/}
            {/*  </Row>*/}
            {/*</Card>*/}

            <Card title="招聘信息" className={styles.card} bordered={false}>
              <Row gutter={16}>
                <Col {...colStyle}>
                  <FormItem name="socialTrainee" label="招聘类型">
                    <Select placeholder="请选择">
                      {socialTraineeStateArray.map((item, index) => {
                        return (
                          <Option value={`${index}`} key={index}>
                            {item}
                          </Option>
                        )
                      })}
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'招聘渠道'} name="channel">
                    <Select placeholder="请选择" showSearch filterOption={filterOption}>
                      {
                        channelList.map((item, index) => {
                          return (
                            <Option value={`${item.value}`} key={item.value}>
                              {item.label}
                            </Option>
                          )
                        })
                      }
                    </Select>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'推荐人(内部)'} name="innerReferrer">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'推荐人(外部)'} name="outerReferrer">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>

                <Col {...colStyle}>
                  <FormItem label={'招聘网站'} name="recruitmentWeb">
                    <Input placeholder="请输入"/>
                  </FormItem>
                </Col>
              </Row>
            </Card>

            <Card title="教育经历" bordered={false} style={{marginBottom:24}}>
              <FormItem name="employeeEducation">
                <EducationTableForm employeeId={employeeId}/>
              </FormItem>
            </Card>

            <Card title="工作经历" bordered={false} style={{marginBottom:24}}>
              <FormItem name="employeeSociety">
                <SocietyTableForm employeeId={employeeId}/>
              </FormItem>
            </Card>

            <Card title="行政党派信息" bordered={false} style={{marginBottom:24}}>
              <FormItem name="employeeInorgname">
                <InOrgNameTableForm employeeId={employeeId}/>
              </FormItem>
            </Card>

            <Card title="家庭成员信息" bordered={false} style={{marginBottom:24}}>
              <FormItem name="familyMember">
                <FamilyTableForm employeeId={employeeId}/>
              </FormItem>
            </Card>
          </PageHeaderWrapper>
        </div>
        <FooterToolbar>
          {getErrorInfo(error)}
          <Button type="primary" size="large" onClick={() => history.goBack()}>返回</Button>
          <Button type="primary" size="large" onClick={() => form?.submit()} loading={submitting}>保存</Button>
        </FooterToolbar>
      </Form> : <div className='spin-block'><Spin size="large"/></div>
  )
}

export default connect(({ infoAndEdit, infoModel, loading }) => ({
  infoModel,
  infoAndEdit,
  submitting: loading.effects['infoAndEdit/updateMainInfo'],
}))(Edit)
